package client;

import bean.User;
import service.UserService;

import javax.security.auth.login.LoginException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        // 1.获取登录页面输入的用户名与密码和验证码
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String verifycode = request.getParameter("verifycode");
        // 2.调用service完成登录操作。
        UserService userService = new UserService();
        HttpSession session = request.getSession();
        String checkcode_server = (String) session.getAttribute("CHECKCODE_SERVER");
        session.removeAttribute("CHECKCODE_SERVER");//确保验证码一次性
        //验证码校验
        if(!checkcode_server.equalsIgnoreCase(verifycode)){
            //提示信息
            request.setAttribute("login_msg","验证码错误！");
            //跳转登录页面
            request.getRequestDispatcher("/login.jsp").forward(request,response);
            return;
        }
        try {//登录验证
            User user =  userService.login(username,password);
            // 3.登录成功，将用户存储到session中.
            request.getSession().setAttribute("user", user);
            //跳转页面,因为request中没有共享数据，所以使用重定向
            response.sendRedirect(request.getContextPath()+"/listUser");

        } catch (LoginException e) {
        //登录失败
        //提示信息
        request.setAttribute("login_msg","用户名或密码错误！");
        //跳转登录页面
        request.getRequestDispatcher("/login.jsp").forward(request,response);
            e.printStackTrace();
            return;
        }

    }
}
